/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view;

import java.awt.Color;
import java.awt.Rectangle;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

import com.dianlian.pss.inter.Connection;
import com.ruipengkj.ApplicationConfig;
import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TEmployee;
import com.ruipengkj.bean.TRight;
import com.ruipengkj.bean.TRole;
import com.ruipengkj.bean.TRoleRight;
import com.ruipengkj.bean.TShop;
import com.ruipengkj.bean.TWorkShift;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.UUID;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.jdbc.ConnectionNetWork;
import com.ruipengkj.service.TEmployeeService;
import com.ruipengkj.service.TShopService;
import com.ruipengkj.service.TWorkShiftService;
import com.sun.awt.AWTUtilities;

/**
 * 说明： 登陆界面
 * 
 * @Author：李智深
 * @Date：2012-03-15
 */
public class RPLogin extends JFrame implements ActionListener, CaretListener {

	private static final long serialVersionUID = 1L;
//	private static Logger log=LogFactory.getInstance().getLogger();
	private JPanel contentPane;
	private JLabel background = new JLabel(
			ImageFactory.loadImage(ImageFactory.LOGIN_BG)); // 在jlabel里添加图片
	private JButton postButton = new JButton(
			ImageFactory.loadImage(ImageFactory.LOGIN_BTN_BG)); // 在按钮里添加图片
	private JButton resetButton = new JButton(
			ImageFactory.loadImage(ImageFactory.LOGIN_BTN_RESET_BG));
	private JButton exitButton = new JButton(
			ImageFactory.loadImage(ImageFactory.LOGIN_BTN_QUIT_BG));
	private JLabel userId = new JLabel();
	private JLabel userPwd = new JLabel();
	private JTextField userIdBox = new JTextField();
	public JPasswordField userPwdBox = new JPasswordField();
	private TEmployeeService tEmployeeService;// 管理登陆
	private TWorkShiftService tWorkShiftService;// 管理交班
	private TShopService tShopService;// 商店
//	private static final String ServiceURL = "http://www.dlwoo.com";

	// 本地版本文件
	static String LocalVerFileName = "ver.txt";

	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		RPLogin rp = new RPLogin();
		rp.setVisible(true);
	}

	private void BuildSpring(boolean isNew) {
		BuildSpringApplication.getInstance(isNew);
		ConnectionNetWork connectionNetWork = new ConnectionNetWork();

		try {// 初始化试图
				// ##采购订单汇总表
			if (connectionNetWork
					.hasTable("ruipengkj_view_purchase_order_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_purchase_order_summary as select  s.Name,p.PurchaseID,p.HappenTime as addTime,sum(b.Num) as orderTotalNumber,sum(b.Price*b.Num) as orderTotalManey,e.Name as empName from ruipeng_tb_tpurchase as p,ruipeng_tb_tbilldetail as b,ruipeng_tb_tsupplier as s,ruipeng_tb_temployee e where p.SupplierID=s.SupplierID and b.BillID=p.PurchaseID and e.EmployeeID=p.Buyer group by p.PurchaseID");
			}

			// ##采购商品汇总表
			if (connectionNetWork
					.hasTable("ruipengkj_view_purchase_commodity_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_purchase_commodity_summary as select c.CommodityID, c.Barcode, c.name as commodityName,sum(b.num) as totalNumber,sum(b.num*b.price) as totalPrice,sum(s.num * c.AvgPrice)/SUM(s.num) as avgPrice from ruipeng_tb_tcommodity as c, ruipeng_tb_tbillDetail as b,ruipeng_tb_tstock as s where c.CommodityID = s.CommodityID and c.CommodityID=b.CommodityID and b.BillType=1 GROUP BY c.CommodityID;");
			}

			// ##采购商品退货汇总表
			if (connectionNetWork
					.hasTable("ruipengkj_view_purchase_commodity_return_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_purchase_commodity_return_summary as select c.commodityID, c.Barcode,c.Name as commodityName,sum(b.Num) as totalNumber,sum(b.Price*b.Num) as totalPrice from ruipeng_tb_tcommodity as c,ruipeng_tb_tbillDetail as b where  b.BillType=2 and c.CommodityID=b.CommodityID GROUP BY c.CommodityID");
			}

			// ##日采购报表
			if (connectionNetWork.hasTable("ruipengkj_view_day_buy_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_day_buy_summary as select p.HappenTime,sum(b.num) as count,sum(b.price*b.num) as buyTotalMoney from ruipeng_tb_tpurchase as p,ruipeng_tb_TCommodity c, ruipeng_tb_tbillDetail as b where c.CommodityID=b.commodityid and b.billType = 1 and b.billId = p.purchaseid group by EXTRACT(YEAR FROM p.HappenTime),EXTRACT(MONTH FROM p.HappenTime),EXTRACT(DAY FROM p.HappenTime)");
			}

			// ##月度采购报表
			if (connectionNetWork.hasTable("ruipengkj_view_month_buy_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_month_buy_summary as select p.HappenTime,sum(b.num) as count,sum(b.price*b.num) as buyTotalMoney from ruipeng_tb_tpurchase as p,ruipeng_tb_TCommodity c, ruipeng_tb_tbillDetail as b where c.CommodityID=b.commodityid and b.billType = 1 and b.billId = p.purchaseid group by EXTRACT(YEAR FROM p.HappenTime),EXTRACT(MONTH FROM p.HappenTime)");
			}

			// ##年度采购报表
			if (connectionNetWork.hasTable("ruipengkj_view_year_buy_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_year_buy_summary as select p.HappenTime,sum(b.num) as count,sum(b.price*b.num) as buyTotalMoney from ruipeng_tb_tpurchase as p,ruipeng_tb_TCommodity c, ruipeng_tb_tbillDetail as b where c.CommodityID=b.commodityid and b.billType = 1 and b.billId = p.purchaseid group by EXTRACT(YEAR FROM p.HappenTime)");
			}

			// ##供货商供货明细表
			if (connectionNetWork
					.hasTable("ruipengkj_view_supplier_detail_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_supplier_detail_summary as Select s.name as supplierName, p.HappenTime as HappenTime, c.name as commodityName, c.unit,b.detailid, b.num, b.price, b.num*b.price as totlePrice,e.Name as buyer, p.operator from ruipeng_tb_tbilldetail as b, ruipeng_tb_tsupplier as s, ruipeng_tb_tcommodity as c, ruipeng_tb_tpurchase as p, ruipeng_tb_temployee as e where b.commodityid = c.commodityid and b.billid = p.purchaseid and b.billType = 1 and EmployeeID=p.Buyer and p.supplierid = s.supplierid");
			}

			// ##仓库库存统计表
			if (connectionNetWork.hasTable("ruipengkj_view_store_stock")) {
				connectionNetWork
						.insert("create view ruipengkj_view_store_stock as Select stock.stockID as id, s.name as storeName, c.barcode, c.name as commodityName, c.unit, c.price as price, stock.num as num, stock.num*c.price as totalPrice from ruipeng_tb_tstore as s, ruipeng_tb_tstock as stock, ruipeng_tb_TCommodity as c where stock.storeid = s.storeid and stock.commodityid = c.commodityid");
			}

			// ##盘点入库单汇总表
			if (connectionNetWork.hasTable("ruipengkj_view_in_stock_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_in_stock_summary as select s.InOutID,s.HappenTime,sum(b.Num) as num,sum(b.num*b.Price) as price from ruipeng_tb_tstockinout as s,ruipeng_tb_tbilldetail as b where s.source=b.billid and s.Type=1 group by s.InOutID;");
			}

			// ##盘点出库单汇总表
			if (connectionNetWork.hasTable("ruipengkj_view_out_stock_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_out_stock_summary as select s.InOutID,s.HappenTime,sum(b.Num) as num,sum(b.num*b.Price) as price from ruipeng_tb_tstockinout as s,ruipeng_tb_tbilldetail as b where s.source=b.billid and s.Type=2 group by s.InOutID;");
			}

			// #销售订单明细表
			if (connectionNetWork.hasTable("ruipengkj_view_order_detail")) {
				connectionNetWork
						.insert("create view ruipengkj_view_order_detail as select c.CommodityID as id,u.UserName,o.OrderID ,o.HappenTime,c.Name,o.NeedMoney ,o.TotalAmount,o.Operator from  ruipeng_tb_TUser as u,ruipeng_tb_TOrder as o ,ruipeng_tb_TCommodity as c where c.CommodityID=o.OrderID and o.UserID=u.UserID");
			}
			// #月度销售报表
			if (connectionNetWork.hasTable("ruipengkj_view_month_sale_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_month_sale_summary as select o.HappenTime,sum(b.num) as count,sum(b.num*b.price) as saleTotalMoney, sum(c.avgPrice*b.num) as saleTotalCost, sum(b.num*b.price)-sum(c.avgPrice*b.num) as saleProfit from ruipeng_tb_TOrder as o,ruipeng_tb_TCommodity c, ruipeng_tb_tbillDetail as b where c.CommodityID=b.commodityid and b.billType = 3 and b.billId = o.OrderID group by EXTRACT(YEAR FROM o.HappenTime),EXTRACT(MONTH FROM o.HappenTime)");
			}
			// #年度销售报表
			if (connectionNetWork.hasTable("ruipengkj_view_year_sale_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_year_sale_summary as select o.HappenTime,sum(b.num) as count,sum(b.num*b.price) as saleTotalMoney, sum(c.avgPrice*b.num) as saleTotalCost, sum(b.num*b.price)-sum(c.avgPrice*b.num) as saleProfit from ruipeng_tb_TOrder as o,ruipeng_tb_TCommodity c, ruipeng_tb_tbillDetail as b where c.CommodityID=b.commodityid and b.billType = 3 and b.billId = o.OrderID group by EXTRACT(YEAR FROM o.HappenTime)");
			}
			// #日度销售报表
			if (connectionNetWork.hasTable("ruipengkj_view_day_sale_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_day_sale_summary as select o.HappenTime,sum(b.num) as count,sum(b.num*b.price) as saleTotalMoney, sum(c.avgPrice*b.num) as saleTotalCost, sum(b.num*b.price)-sum(c.avgPrice*b.num) as saleProfit from ruipeng_tb_TOrder as o,ruipeng_tb_TCommodity c, ruipeng_tb_tbillDetail as b where c.CommodityID=b.commodityid and b.billType = 3 and b.billId = o.OrderID group by EXTRACT(YEAR FROM o.HappenTime),EXTRACT(MONTH FROM o.HappenTime),EXTRACT(DAY FROM o.HappenTime)");
			}
			// ##商品销售汇总表
			if (connectionNetWork
					.hasTable("ruipengkj_view_commodity_order_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_commodity_order_summary as select c.commodityID as commodityID, c.Name as commodityName,sum(b.Num) as totalNumber,sum(b.Num*b.Price) as totalPrice from ruipeng_tb_tcommodity as c, ruipeng_tb_tbillDetail as b where  b.BillType=3 and c.CommodityID=b.CommodityID GROUP BY c.CommodityID");
			}
			// ##商品销售退货汇总表
			if (connectionNetWork
					.hasTable("ruipengkj_view_commodity_order_return_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_commodity_order_return_summary as select c.commodityID as commodityID, c.Name as commodityName,sum(b.Num) as totalNumber,sum(b.Num*b.Price) as totalPrice from ruipeng_tb_tcommodity as c, ruipeng_tb_tbillDetail as b where  b.BillType=4 and c.CommodityID=b.CommodityID GROUP BY c.CommodityID");
			}
			// ##商品出入库单汇总表
			if (connectionNetWork
					.hasTable("ruipengkj_view_commodity_out_in_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_commodity_out_in_summary as select c.commodityID as commodityID, c.Name as commodityName,c.Unit,sum(sod.Num) as totalNumber,sum(sod.Num*c.price) totalPrice,so.type, CONCAT(c.commodityid, so.type) as id from ruipeng_tb_tcommodity as c,ruipeng_tb_TStockInOut so,ruipeng_tb_TStockInOutDetail as sod where so.InOutID=sod.InOutID and c.commodityID=sod.commodityID GROUP BY c.CommodityID, so.type");
			}

			// ##会员销售汇总表
			if (connectionNetWork
					.hasTable("ruipengkj_view_menber_sales_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_menber_sales_summary as select u.userID,u.RealName as userName,u.BuyCount,sum(b.num) as buyTotalNumber,sum(b.num*b.price) as totalBuyMoney,sum(b.num*c.AvgPrice) as totalCost,(sum(b.num*b.price)-sum(b.num*c.AvgPrice)) as totalProfit,LastLoginTime as lastDate from ruipeng_tb_tuser u,ruipeng_tb_torder as o,ruipeng_tb_tbillDetail as b ,ruipeng_tb_tcommodity as c where u.UserID=o.UserID and o.OrderID=b.BillID and b.commodityID=c.commodityid GROUP BY u.userID");
			}

			// ##商品毛利润表
			if (connectionNetWork.hasTable("ruipengkj_view_profit_commodity")) {
				connectionNetWork
						.insert("create view ruipengkj_view_profit_commodity as Select c.commodityid as id, c.name,c.unit,sum(b.num) as totalNum,sum(b.num*c.avgPrice) as totalBatchPrice,sum(b.num*c.price) as totalPrice, sum(b.num*(b.price-c.avgPrice)) as profit,(sum(b.num*b.price-b.num*c.avgPrice)/sum(b.num*c.avgPrice)) as profitRate from ruipeng_tb_tcommodity as c,ruipeng_tb_tbilldetail as b where c.commodityid=b.commodityid and b.billtype = 3 group by c.commodityid;");
			}

			// ##经营业绩表
			if (connectionNetWork
					.hasTable("ruipengkj_view_business_performance")) {
				connectionNetWork
						.insert("create view ruipengkj_view_business_performance as select b.billType as type, sum(b.num*b.price) as totalPrice from ruipeng_tb_tbilldetail as b group by b.billType");
			}

			// ##盈利亏损汇总表
			if (connectionNetWork
					.hasTable("ruipengkj_view_surplus_order_summary")) {
				connectionNetWork
						.insert("create view ruipengkj_view_surplus_order_summary as select o.orderid,o.HappenTime as addTime,sum(b.num) as totalNumber,sum(b.num*b.price) as totalPrice ,(sum(b.price*b.num)-sum(c.avgPrice*b.num)) as surplus from ruipeng_tb_torder as o,ruipeng_tb_tbilldetail as b,ruipeng_tb_tcommodity as c where o.orderid=b.billid and b.billType = 3 and b.commodityid=c.commodityid group by o.orderid");
			}

			// 初始化数据，权限等……
			openTextInString(connectionNetWork, new File("table/initRight.sql"));
			connectionNetWork.close();
		} catch (Exception e1) {
			// e1.printStackTrace();
		} finally {
			connectionNetWork.close();
		}
	}

	public RPLogin() {
		BuildSpring(true);
		this.setUndecorated(true);
		AWTUtilities.setWindowOpaque(this, false);
		tEmployeeService = BuildSpringApplication.getInstance()
				.getTEmployeeServiceImpl();
		tWorkShiftService = BuildSpringApplication.getInstance()
				.getTWorkShiftServiceImpl();
		tShopService = BuildSpringApplication.getInstance()
				.getTShopServiceImpl();
		this.setResizable(false);
		this.setSize(435, 332);
		this.setLocation(Util.getWidth() / 2 - 217, Util.getHeight() / 2 - 166);
		this.setTitle(ApplicationConfig.APP_TITLE);
		this.setIconImage(ApplicationConfig.APP_IMAGE);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.init();
		this.initListener();
	}

	public void init() {
		this.getRootPane().setDefaultButton(postButton);
		contentPane = (JPanel) getContentPane();
		contentPane.setLayout(null);
		contentPane.grabFocus();

		background.setBounds(new Rectangle(1, 1, 430, 297));
		postButton.setBounds(new Rectangle(74, 225, 84, 34));
		postButton.setRolloverIcon(ImageFactory
				.loadImage(ImageFactory.LOGIN_SELECT_BTN_BG));
		postButton.setFocusPainted(false);
		postButton.setBorderPainted(false);
		postButton.setContentAreaFilled(false);
		postButton.setCursor(Util.CURSOR_HAND);

		resetButton.setBounds(new Rectangle(268, 225, 84, 34));
		resetButton.setRolloverIcon(ImageFactory
				.loadImage(ImageFactory.LOGIN_SELECT_BTN_RESET_BG));
		resetButton.setFocusPainted(false);
		resetButton.setBorderPainted(false);
		resetButton.setContentAreaFilled(false);
		resetButton.setCursor(Util.CURSOR_HAND);

		exitButton.setBounds(new Rectangle(171, 225, 84, 34));
		exitButton.setRolloverIcon(ImageFactory
				.loadImage(ImageFactory.LOGIN_SELECT_BTN_QUIT_BG));
		exitButton.setFocusPainted(false);
		exitButton.setBorderPainted(false);
		exitButton.setContentAreaFilled(false);
		exitButton.setCursor(Util.CURSOR_HAND);
		userId.setText("用户名：");
		userPwd.setText("密  码：");

		userId.setIcon(ImageFactory.loadImage(ImageFactory.ICON_7));
		userPwd.setIcon(ImageFactory.loadImage(ImageFactory.ICON_7));

		userId.setBounds(new Rectangle(98, 128, 62, 18));
		userPwd.setBounds(new Rectangle(98, 166, 62, 14));

		userIdBox.setBounds(new Rectangle(160, 125, 174, 24));
		userPwdBox.setBounds(new Rectangle(160, 160, 174, 24));

		userIdBox.addFocusListener(new Login_userIdBox_focusAdapter(this));
		userPwdBox.addFocusListener(new Login_userPwdBox_focusAdapter(this));

		this.userIdBox.setBorder(BorderFactory
				.createLineBorder(SystemColor.inactiveCaption));
		this.userPwdBox.setBorder(BorderFactory
				.createLineBorder(SystemColor.inactiveCaption));

		userPwdBox.setDisabledTextColor(Color.black);
		userPwdBox.setSelectionColor(Color.black);

		contentPane.add(resetButton);
		contentPane.add(postButton);
		contentPane.add(exitButton);
		contentPane.add(userId);
		contentPane.add(userIdBox);
		contentPane.add(userPwdBox);
		contentPane.add(userPwd);
		contentPane.add(background);

		MoveListener moveListener = new MoveListener();
		this.addMouseListener(moveListener);
		this.addMouseMotionListener(moveListener);
	}

	private void initListener() {
		resetButton.addActionListener(this);
		postButton.addActionListener(this);
		exitButton.addActionListener(this);
		userIdBox.addCaretListener(this);
	}

	// 读取文件字符串
	private static void openTextInString(ConnectionNetWork connectionNetWork,
			File file) throws Exception {
		FileInputStream fis = new FileInputStream(file);
		BufferedInputStream bis = new BufferedInputStream(fis);
		int len = 0;
		byte[] b = new byte[1024];
		StringBuffer sb = new StringBuffer();
		while (true) {
			len = bis.read(b, 0, b.length);
			if (len == -1) {
				break;
			}
			sb.append(new String(b, 0, len, "UTF-8"));
		}

		String str[] = sb.toString().split(";");
		for (int i = 0, length = str.length; i < length; ++i) {
			ApplicationConfig.INIT_PROGRESS++;
//			 log.info(str[i]+";");
			connectionNetWork.insert(str[i] + ";");
		}
	}

	// 事件
	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == postButton) {
			// 登陆
			String username = userIdBox.getText();
			String pwd = String.copyValueOf(userPwdBox.getPassword());

			if (username.equals("") || username.length() > 20) {
				JOptionPane.showMessageDialog(null, "用户名不能为空，且不能大于20个字");
				return;
			}
			if (pwd.equals("") || pwd.length() > 20) {
				JOptionPane.showMessageDialog(null, "密码不能为空，且不能大于20个字");
				return;
			}

			try {
				TEmployee tEmployee = tEmployeeService.login(username, pwd);
				
				if (tEmployee != null) {
					if (!tEmployee.getUserName().equals(username) || !tEmployee.getPassword().equals(pwd)) {
						JOptionPane.showMessageDialog(null, "登陆失败，用户名密码错误");
						return;
					}
					if (!tEmployee.isIsValid()) {
						JOptionPane.showMessageDialog(null, "当前员工账号无效，请与管理员联系");
						return;
					}
					ApplicationContext.EMPLOYEE = tEmployee;
					ApplicationContext.OPERATOR_NAME = tEmployee.getName();
					ApplicationContext.OPERATOR_ID = tEmployee.getEmployeeID();
					ApplicationContext.EMPLOYEE_SN = tEmployee.getEmployeeSn();
					TRole role = tEmployee.getTRole();
					ApplicationContext.ROLE = role;
					if (role != null) {
						Set<TRoleRight> set = role.getTRoleRights();
						if (set != null && set.size() != 0) {
							Iterator<TRoleRight> it = set.iterator();
							while (it.hasNext()) {
								TRoleRight roleRight = it.next();
								TRight right = roleRight.getTRight();
								if (right != null) {
									ApplicationContext.TRIGHT_LIST.add(right
											.getLevel());
//									System.out.println(right.getLevel());
//									System.out.println(right.getName());
								}
							}
							ApplicationContext.OPERATOR_ROLE_NAME = role
									.getName();
							this.initRPMain();
						} else {
							JOptionPane.showMessageDialog(null, "您没有登陆该软件的权限");
						}
					} else {
						JOptionPane.showMessageDialog(null, "您没有登陆该软件的权限");
					}
				} else {
					JOptionPane.showMessageDialog(null, "登陆失败，用户名密码错误");
					return;
				}
				TWorkShift tws = tWorkShiftService
						.findLastOneByEmployee(ApplicationContext.EMPLOYEE
								.getEmployeeID());
				if (tws != null) {
					ApplicationContext.WORKSHIFT_ID = tws.getWorkShiftID();
				} else {
					tws = new TWorkShift();
					tws.setToEmployeeID(ApplicationContext.EMPLOYEE
							.getEmployeeID());
					tws.setWorkShiftID(UUID.GenUUID15());
					tws.setStatus(ApplicationContext.WORKSHIFT_STATUS1);
					String WorkShiftID = (String) tWorkShiftService
							.saveRetService(tws);
					ApplicationContext.WORKSHIFT_ID = WorkShiftID;
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} else if (e.getSource() == exitButton) {
			// 退出
			System.exit(0);
		} else if (e.getSource() == resetButton) {
			// 设置数据库
			SetSqlDialog setSqlDialog = new SetSqlDialog(null, "数据库设置", true);
			if (setSqlDialog.isSuccess == 1) {
				if (Util.showConfirmDialog("创建数据库成功，需要重启软件，现在重启吗？") == 0) {
					dispose();
					thread.start();
				}
			} else if (setSqlDialog.isSuccess == 2) {
				if (Util.showConfirmDialog("连接数据库成功，需要重启软件，现在重启吗？") == 0) {
					dispose();
					thread.start();
				}
			}
		}
	}

	Thread thread = new Thread() {
		public void run() {
			try {
				Thread.sleep(3000);
				new InitMain().setVisible(true);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		};
	};

	private void initRPMain() {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					List<TShop> list = tShopService.findService(null);

					if (list == null || list.size() == 0) {
						JOptionPane
								.showMessageDialog(null, "商店信息未配置，请先配置商店信息！");
					} else {
						TShop tShop = list.get(0);
						if (tShop.getSiteUserName() == null
								|| tShop.getSitePwd() == null) {
							JOptionPane.showMessageDialog(null,
									"商店信息未正确配置，请先配置商店信息！");
						} else {
							ApplicationContext.SHOP_INFO = list.get(0);
							ApplicationContext.conn = new Connection(
									ApplicationContext.SHOP_INFO.getShopID(),
									"clientID", ApplicationContext.SHOP_INFO
											.getSiteUserName(),
									ApplicationContext.SHOP_INFO.getSitePwd());
						}
					}
				} catch (Exception e) {

					e.printStackTrace();
				}
				RPMain main = new RPMain();
				dispose();
				main.setVisible(true);
			}
		});
	}

	public void resetButton_actionPerformed(ActionEvent e) {

	}

	public void setBorderColor(int s, Color c) {
		if (s == 0) {
			this.userIdBox.setBorder(BorderFactory.createLineBorder(c));
		} else if (s == 1) {
			this.userPwdBox.setBorder(BorderFactory.createLineBorder(c));
		}
	}

	public void userIdBox_focusGained(FocusEvent e) {
		this.setBorderColor(0, new Color(158, 204, 0));
	}

	public void userIdBox_focusLost(FocusEvent e) {
		this.setBorderColor(0, SystemColor.inactiveCaption);
	}

	public void userPwdBox_focusGained(FocusEvent e) {
		this.setBorderColor(1, new Color(158, 204, 0));
	}

	public void userPwdBox_focusLost(FocusEvent e) {
		this.setBorderColor(1, SystemColor.inactiveCaption);
	}

	String idText = "";// 储存未改变时，id的字符串

	@Override
	public void caretUpdate(CaretEvent e) {
		if (!((JTextField) e.getSource()).getText().equals(idText)) {
			// 当id的字符串改变时，清空密码框
			userPwdBox.setText("");
			idText = ((JTextField) e.getSource()).getText();
		}
	}

}

class Login_userPwdBox_focusAdapter extends FocusAdapter {
	private RPLogin adaptee;

	Login_userPwdBox_focusAdapter(RPLogin adaptee) {
		this.adaptee = adaptee;
	}

	public void focusGained(FocusEvent e) {
		adaptee.userPwdBox_focusGained(e);
	}

	public void focusLost(FocusEvent e) {
		adaptee.userPwdBox_focusLost(e);
	}
}

class Login_userIdBox_focusAdapter extends FocusAdapter {
	private RPLogin adaptee;

	Login_userIdBox_focusAdapter(RPLogin adaptee) {
		this.adaptee = adaptee;
	}

	public void focusGained(FocusEvent e) {
		adaptee.userIdBox_focusGained(e);
	}

	public void focusLost(FocusEvent e) {
		adaptee.userIdBox_focusLost(e);
	}
}
